﻿/* --------------------------------------------
* list.common.js
* 创建：江怀玉
* 日期: 2014.11.30
* 依赖于YUI2.9.0  
* --------------------------------------------*/
var PageTotal, pageindex = 1, pagesize = 25, editpageFlag = 0, _ListPage = "datagrid";
var _isNotToolBar = "No";
//alert( document.location);
if ( document.location.toString().indexOf("NoToolBar") > 0) {
    _isNotToolBar = "Yes";
    //alert(_isNotToolBar);
}
//debugger
var datapage = _IsNoEntity != "Y" ? "/Extend/AjaxData/JSONList.aspx" : "/Extend/AjaxData/DataTableJSONList.aspx";
/*重新加载数据*/
function LoadData() {
    var requestStr = "pagesize=" + pagesize + "&pageindex=" + pageindex + "&entity=" + const_entityName + "&order=" + const_Order + "&r=" + Math.random() + "&zip=94089&results=10&output=json&functionid=" + const_functionId + "&customCondition=" + const_CustomCondition + "&condition=" + const_Condition;
    mDataTable.requery(requestStr);
}


//刷新数据
function RefreshData() {
    initialRequestUrl = "pageindex=1&entity=" + const_entityName + "&order=" + const_Order + "&r=" + Math.random() + "&zip=94089&results=10&output=json&functionid=" + const_functionId + "&customCondition=" + /*decodeURI*/(const_CustomCondition) + "&condition=" + const_Condition;
    pageindex = 1;
    if (!(this.location.href.indexOf("MasterDetailList") > 0)) {
        //RefreshCache();
    }
    ReLoadData();
}

/*刷新时候调用*/
function ReLoadData() {
    var requestStr = "pagesize=" + pagesize + "&pageindex=" + pageindex + "&entity=" + const_entityName + "&order=" + const_Order + "&r=" + Math.random() + "&zip=94089&results=10&output=json&functionid=" + const_functionId + "&customCondition=" + const_CustomCondition + "&condition=" + const_Condition;
    GetTotal(datapage + "?onlyTotal=true&" + requestStr);
    mDataTable.requery(requestStr);
    fnCreateChkAllCheckBox();
}

/*关闭窗口*/
function closeWin() {
    if (typeof (customCloseWin) == "function") {
        customCloseWin();
    }
    else {
        YAHOO.example.container.dialog1.hide();
        LoadData();
    }
}

/* 对应的方法和ID*/
var _fn, _id;
function ShowDialog(fn, id, src) {
    _fn = fn;
    _id = id;
    document.getElementById("EditUIWindow1").src = src;
    YAHOO.example.container.dialog2.show();
}


/*数据绑定*/
function BindData() {
    YAHOO.example.XHR_JSON = function () {
        /*定义数据*/
        var myColumnDefs = const_DataFields;
        /*定义数据请求*/
        if (requireUrl == "") {
            requireUrl = datapage + "?";
        }
        var myDataSource = new YAHOO.util.DataSource(requireUrl);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
        myDataSource.connXhrMode = "queueRequests";
        /*定义数据源的请求结构*/
        myDataSource.responseSchema = {
            resultsList: "rows",
            metaFields: { totalRecords: "total" },
            fields: const_DataColums
        };
        this.myDataTable = new YAHOO.widget.ScrollingDataTable("json", myColumnDefs,
                    myDataSource,
                    {
                        initialRequest: initialRequestUrl,
                        selectionMode: "single",
                        height: (Dom.getViewportHeight() -(_isNotToolBar=="Yes"?65 : 95)) + "px",
                        //width: "500px"
                        width: (Dom.getViewportWidth() + 15) + "px"
                    });

        mDataTable = this.myDataTable;
        var mySuccessHandler = function () {
            this.set("sortedBy", null);
            this.onDataReturnAppendRows.apply(this, arguments);
        };

        var myFailureHandler = function () {
            //this.showTableMessage(YAHOO.widget.DataTable.MSG_ERROR, YAHOO.widget.DataTable.CLASS_ERROR);
            this.showTableMessage("没有数据", "没有数据");
            this.onDataReturnAppendRows.apply(this, arguments);

        };

        // 定义回传方法
        var callbackObj = {
            success: mySuccessHandler,
            failure: myFailureHandler,
            scope: myDataTable
        };


        // 调用自定义双击行的方法
        var onRowDoubleClick = function () {
            if (typeof (CustomDbClick) == "function") {
                CustomDbClick();
            } else {
                if (typeof (fnView) == "function") {
                    fnView("e");
                }
            }
        };

        //单元格单击事件
        var onCellClick = function (e) {
            //            var ctrl = event.srcElement||e;
            //            if (ctrl.nodeName == "DIV") {
            //                if (ctrl != _o) {
            //                    var o = document.getElementById("tx");
            //                    if (o != undefined) {
            //                        _o.innerHTML = document.getElementById("tx").value;
            //                    }
            //                }
            //                _o = ctrl;
            //                var ctrl2 = "<input id='tx' width='100%' onblur='ontest(this)' value='" + ctrl.innerHTML + "'>";
            //                ctrl.innerHTML = ctrl2;
            //                var o = document.getElementById("tx");
            //                o.focus();
            //                //alert(ctrl.innerHTML);
            //            }
        }

        // 注册相关方法给相关事件
        this.myDataTable.subscribe("rowMouseoverEvent", this.myDataTable.onEventHighlightRow);
        this.myDataTable.subscribe("rowMouseoutEvent", this.myDataTable.onEventUnhighlightRow);
        this.myDataTable.subscribe("rowClickEvent", this.myDataTable.onEventSelectRow);
        this.myDataTable.subscribe("cellClickEvent", this.myDataTable.onEventShowCellEditor);
        this.myDataTable.subscribe("cellClickEvent", onCellClick);
        this.myDataTable.subscribe("rowDblclickEvent", onRowDoubleClick);

        this.myDataTable.subscribe("checkboxClickEvent", function (oArgs) {
            var elCheckbox = oArgs.target;
            var oRecord = this.getRecord(elCheckbox);
            oRecord.setData("iSun_Selected", elCheckbox.checked);
        });

        // Programmatically select the first row 
        this.myDataTable.selectRow(this.myDataTable.getTrEl(0));

        hideCol();
        //自定义隐藏列
        if (typeof (customFnHideCol) == "function") {
            customFnHideCol();
        }
        fnCreateChkAllCheckBox();

        //fnFixTableHeader();
    } ();
}

/*------------------------------------------------
// 窗口最大化
------------------------------------------------*/
var fnSetWindowMax = function () {
    //    var _dialog1 = window.document.getElementById("dialog1");
    //    //var aHref = dialog1.getElementsByTagName("A")[0];
    //    var el = document.createElement("a");
    //    el.href = "#";
    //    el.innerText = "[大]";
    //    el.setAttribute("style", "position:absolute;top:5px;right:25px;width:25px;height:15px;background:url(sprite.png) no-repeat 0 -300px;cursor:pointer");
    //    el.setAttribute("onclick", "SetMaxWin()");
    //    //_dialog1.insertBefore(el,_dialog1.getElementsByTagName("A")[0]);
    //    //ea.parentNode.insertBefore(pEl, galleryEl); 
    //    var ea = _dialog1.getElementsByTagName("A")[0];
    //    ea.parentNode.insertBefore(el, ea);

}
var SetMaxWin = function () {
    var ctrl = event.srcElement;
    if (ctrl.innerText == "[大]") {
        SetMaxDWH(YAHOO.example.container.dialog1);
    } else {
        SetNorDWH(YAHOO.example.container.dialog1);
    }
    //ctrl.innerText = ctrl.innerText == "[大]" ? "[小]" : "[大]";
    YAHOO.example.container.dialog1.dragEvent.fire();
}

/// ----------------------------
///  
/// ----------------------------
var fnFixTableHeader = function () {
    var els = document.getElementsByTagName("table");
    for (i = 0; i < els.length; i++) {
        var el = els[0].getElementsByTagName("thead")[0].getElementsByTagName("tr")[0];
        //alert(el);
        var className = (el.getAttribute("class"));
        el.setAttribute("class", className + " " + "FixedTitleRow");
        //alert(el.getAttribute("class"));
    }
}

var fnCreateChkAllCheckBox = function () {
    if ((document.getElementById("chkAll")) == null) {
        var e1 = window.document.getElementById("yui-dt16-th-iSun_Selected");
        if (e1 == null) {
            e1 = window.document.getElementById("yui-dt27-th-iSun_Selected");
        }
        if (e1 == null) {
            return;
        }
        if (typeof (e1) != "undefined") {
            var in1 = e1.firstChild;
            var el = document.createElement("input");
            el.setAttribute("type", "checkbox");
            el.setAttribute("id", "chkAll");
            el.setAttribute("onclick", "fnChkAll()");
            el.setAttribute("style", "margin-left:0px;margin-top:0px;z-index:200")
            if (typeof (in1) != "undefined" && in1 != null) {
                in1.insertBefore(el);
            }
        }
    }
}

var fnChkAll = function () {

    var ck = document.getElementsByTagName("input");
    for (var i = 0; i < ck.length; i++) {
        if (ck[i].getAttribute("type") == "checkbox" & ck[i].id != "checkAndOr") {
            ck[i].checked = document.getElementById("chkAll").checked;
            if (mDataTable._oRecordSet._records[i] != undefined) {
                mDataTable._oRecordSet._records[i]._oData.iSun_Selected = ck[i].checked;
            }
        }
    }
}
//隐藏/栏位
function hideCol() { mDataTable.hideColumn(parseInt(0)); mDataTable.refreshView(); };

var _o;
function ontest(o) {
    _o.innerHTML = o.value;
    var f = (_o.parentNode.className.split(' ')[1].replace('yui-dt-col-', ''));
    setValue(f, o.value);
    _o = undefined;
}

///f=字段名 v=值
var temparr = [];
var setValue = function (f, v) {
    var recordID = mDataTable.getSelectedRows()[0];
    var record = mDataTable.getRecord(recordID);
    record._oData[f] = v;
    temparr.join(record._oData);
}




/* -----------------------------------------
*  定义对话窗口功能
*  
*
*
*--------------------------------------------*/
YAHOO.util.Event.addListener(window, "load", BindData);
YAHOO.namespace("example.container");
YAHOO.util.Event.onDOMReady(function () {
    // Define various event handlers for Dialog
    var handleSubmit = function () {
        var editwindow = document.getElementById("EditUIWindow");
        if (editwindow) {
            if (typeof (editwindow.contentWindow.Save) != "undefined") {
                editwindow.contentWindow.Save();
            }
        }
    };

    var handleCancel = function () {
        this.cancel();
    };

    var handleSubmit1 = function () {
        var editwindow = document.getElementById("EditUIWindow1");
        if (editwindow) {
            editwindow.contentWindow.ChooseInfo();
        }
        this.cancel();
    }
    var handleSuccess = function (o) {
        var response = o.responseText;
        response = response.split("<!")[0];
        document.getElementById("resp").innerHTML = response;
    };
    var handleFailure = function (o) {
        alert("Submission failed: " + o.status);
    };

    // Remove progressively enhanced content class, just before creating the module
    YAHOO.util.Dom.removeClass("dialog1", "yui-pe-content");

    /*
    数据编辑
    
    */
    //debugger
    YAHOO.example.container.dialog1 = new YAHOO.widget.Dialog("dialog1",
							    { width: const_EditWindowWidth,
							        height: const_EditWindowHeight,
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        max: true,
							        autofillheight: "body",
							        modal: true,
							        constraintoviewport: true,
							        buttons: [{ text: "保存", handler: handleSubmit, isDefault: true },
								          { text: "取消", handler: handleCancel}]
							    });

    /*
    
    */
    YAHOO.example.container.dialog2 = new YAHOO.widget.Dialog("dialog2",
							    { width: "550px",
							        height: "450px",
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        modal: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [{ text: "保存", handler: handleSubmit1, isDefault: true },
								          { text: "取消", handler: handleCancel}]
							    });

    /*
    
    */
    YAHOO.example.container.dialog3 = new YAHOO.widget.Dialog("dialog3",
							    { width: "350px",
							        height: "100px",
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        modal: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [{ text: "确定", handler: DeleteData, isDefault: true },
								          { text: "取消", handler: handleCancel}]
							    });

    /*
    查询
    */
    YAHOO.example.container.dialog4 = new YAHOO.widget.Dialog("dialog4",
							    { width: "650px",
							        height: "350px",
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        modal: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [
							    { text: "取消", handler: handleCancel}]
							    });

    /**/
    YAHOO.example.container.dialog5 = new YAHOO.widget.Dialog("dialog5",
							    { width: const_EditWindowWidth,
							        height: const_EditWindowHeight,
							        fixedcenter: true,
							        visible: false,
							        draggable: true,
							        close: true,
							        modal: true,
							        autofillheight: "body",
							        constraintoviewport: true,
							        buttons: [
							    { text: "取消", handler: handleCancel}]
							    });
    // Validate the entries in the form to require that both first and last name are entered


    // Wire up the success and failure handlers
    YAHOO.example.container.dialog1.callback = { success: handleSuccess,
        failure: handleFailure
    };

    // Render the Dialog
    YAHOO.example.container.dialog1.render(); //编辑对话框
    YAHOO.example.container.dialog2.render(); //删除对话框
    YAHOO.example.container.dialog3.render(); //
    YAHOO.example.container.dialog4.render(); //
    YAHOO.example.container.dialog5.render(); //

    fnSetWindowMax();



    //----------------------------------------------------*/
    // YAHOO.util.Event.addListener("btnAddNew", "click", YAHOO.example.container.dialog1.show, YAHOO.example.container.dialog1, true);
    // 拖动大小
    var resize = new YAHOO.util.Resize("dialog1", {
        handles: ["br"],
        autoRatio: false,
        minWidth: 450,
        minHeight: 400,
        status: false
    });
    resize.on("startResize", function (args) {
        if (this.cfg.getProperty("constraintoviewport")) {
            var D = YAHOO.util.Dom;
            var clientRegion = D.getClientRegion();
            var elRegion = D.getRegion(this.element);
            resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
            resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET);
        } else {
            resize.set("maxWidth", null);
            resize.set("maxHeight", null);
        }

    }, YAHOO.example.container.dialog1, true);
    resize.on("resize", function (args) {
        var panelHeight = args.height;
        this.cfg.setProperty("height", panelHeight + "px");
    }, YAHOO.example.container.dialog1, true);

});



// 设置对话框的大小
var SetDWH = function (width, height, dialog) {

    var elements = YAHOO.util.Dom.getElementsByClassName('bd', 'div')[0];
    var w = [],
        h = [];
    w.push(width);
    h.push(height);
    dialog.configWidth(null, w);
    dialog.configHeight(null, h);

    dialog.render();
    if (elements) {
        dialog.fillHeight(elements);
    }
}
// 设窗口最大化
var SetMaxDWH = function (dialog) {

    var w = Y.util.Dom.getViewportWidth() - 20;
    var h = Y.util.Dom.getViewportHeight() - 20;
    SetDWH(w, h, dialog);
}

var SetNorDWH = function (dialog) {
    SetDWH(const_EditWindowWidth, const_EditWindowHeight, dialog);
}



/// 用于数据刷新
YAHOO.widget.DataTable.prototype.requery = function (newRequest) {
    var ds = this.getDataSource();
    if (ds instanceof YAHOO.util.LocalDataSource) {
        ds.liveData = newRequest;
        ds.sendRequest("",
			{
			    success: this.onDataReturnInitializeTable,
			    failure: this.onDataReturnInitializeTable,
			    scope: this
			}
		);
    } else {
        ds.sendRequest(
			(newRequest === undefined ? this.get('initialRequest') : newRequest),
			{
			    success: this.onDataReturnInitializeTable,
			    failure: this.onDataReturnInitializeTable,
			    scope: this
			}
		);
    }
};





// 获取最新记录的总数
var record = 0;
var GetTotal = function (url) {
    YAHOO.util.Connect.asyncRequest('POST', url, {
        success: function (res) {
            var o = eval(res.responseText);
            SetPaging(o[0].total);
            record = o[0].total;
            if (document.getElementById("pagetotal") != null) {
                document.getElementById("pagetotal").innerHTML = "<b>共<font color=\"red\">" + o[0].total + "</font>笔记录</b>";
            }

            if (o[0].total == 0) {
                setTimeout('mDataTable.showTableMessage("没有数据", "没有数据")', 1000);
            }
        },
        failure: function (error) {
            //alert("数据错误：" + error.statusText);
        }
    }, null);
}


/*---------------------------------------
// 分页使用
---------------------------------------*/
var fnSplitPage = function () {
    GetTotal(datapage + "?onlyTotal=true&" + initialRequestUrl);
}
setTimeout(fnSplitPage, 100);






var _state = {};
/*-----------------------------------------
* 页面跳转
* 
*
-----------------------------------------*/
var fnGoPage = function () {
    // debugger
    var _page = window.document.getElementById("PageNo");
    fnGetPage(parseInt(_page.value));
}
var fnGetPage = function (page) {
    _state.page = page;
    Ex.handlePagination(_state);
    setTimeout(Ex.paginator.setState(_state), 100);
}


// 分页方法
var Ex = YAHOO.namespace('example');
var SetPaging = function (total) {
    Ex.handlePagination = function (state) {
        _state = state;

        pageindex = state.page;
        pagesize = Ex.Config.rowsPerPage;
        var requestStr = "pagesize=" + Ex.Config.rowsPerPage + "&pageindex=" + pageindex + "&entity=" + const_entityName + "&order=" + const_Order + "&r=" + Math.random() + "&zip=94089&results=10&output=json&functionid=" + const_functionId + "&customCondition=" + const_CustomCondition + "&condition=" + const_Condition;
        myDataTable.requery(requestStr);
        Ex.paginator.setState(state);
    };
    // Create the Paginator widget and subscribe to its changeRequest event
    Ex.Config = {
        rowsPerPage: 25,
        firstPageLinkLabel: "第一页",
        lastPageLinkLabel: "尾页",
        previousPageLinkLabel: "上一页",
        nextPageLinkLabel: "下一页",
        totalRecords: total,
        containers: 'page'
    };
    Ex.paginator = new YAHOO.widget.Paginator(Ex.Config);
    Ex.paginator.subscribe('changeRequest', Ex.handlePagination);
    Ex.paginator.render();
}




//动态加载JS
var fnLoadJSScript = function (url) {
    if (typeof ($) != "undefined") {
        $.getScript(url, function (response, status) { });
    } else {
        loadJS(url);
    }
}


//加载JS
var loadJS = function (src, charset, callback) {
    var head = document.getElementsByTagName("head")[0];

    var script = document.createElement('script');

    script.onload = script.onreadystatechange = script.onerror = function (){ 
        if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) return;

        script.onload = script.onreadystatechange = script.onerror = null;
        script.src = '';
        script.parentNode.removeChild(script);
        script = null;
        if (typeof (callback) == "undefined") {
            callback();
        }
    };

    script.charset = charset || document.charset || document.characterSet || 'gb2312';
    script.src = src;

    try {
        head.appendChild(script);
    } catch (exp) { }
};

loadJS("");